package com.newenergy.wisehome.gateway.device;


import android.app.AlertDialog;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;

import com.jude.easyrecyclerview.EasyRecyclerView;
import com.newenergy.wisehome.R;
import com.newenergy.wisehome.data.bean.BLDeviceInfo;
import com.newenergy.wisehome.data.ormlite.dao.BLDeviceInfoDao;
import com.newenergy.wisehome.gateway.adapter.DnaDeviceAdapter;
import com.newenergy.wisehome.gateway.common.BLModelUtil;
import com.newenergy.wisehome.gateway.manager.BLLocalFamilyManager;
import com.newenergy.wisehome.ui.fragment.BaseFragment;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.com.broadlink.sdk.BLLet;
import cn.com.broadlink.sdk.data.controller.BLDNADevice;
import cn.com.broadlink.sdk.interfaces.controller.BLDeviceScanListener;

/**
 * A simple {@link Fragment} subclass.
 */
public class SearchDnaDeviceFragment extends BaseFragment {

    private ArrayList<BLDNADevice> mData;
    private DnaDeviceAdapter mAdapter;


    @BindView(R.id.rv_search_device)
    EasyRecyclerView mRecyclerView;

    private Handler mHandler = new Handler(Looper.getMainLooper());

    @Override
    public int getLayoutId() {
        return R.layout.fragment_search_dna_device;
    }

    @Override
    public void init(View rootView) {
        mData = new ArrayList<BLDNADevice>();
        mAdapter = new DnaDeviceAdapter(getContext());
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));

        mAdapter.setOnItemClickListener(position -> {
            addDnaDeviceToSdk(position);
        });
        mAdapter.setOnItemLongClickListener(position -> {
            delDnaDevice(position);
            return true;
        });
    }

    private void delDnaDevice(int position) {
        BLDNADevice device = mAdapter.getItem(position);
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle("提示")
                .setMessage("是否删除设备")
                .setNegativeButton("取消", (dialog, which) -> {
                    dialog.dismiss();
                })
                .setPositiveButton("确定", (dialog, which) -> {
                    dialog.dismiss();
                    BLLocalFamilyManager familyManager = BLLocalFamilyManager.getInstance();
                    familyManager.delLocalDevice(device);
                    mAdapter.remove(position);
                });
        builder.show();
    }

    private void addDnaDeviceToSdk(int position) {
        BLDNADevice device = mAdapter.getItem(position);
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle("提示")
                .setMessage("是否添加设备到Sdk")
                .setNegativeButton("取消", (dialog, which) -> {
                    dialog.dismiss();
                })
                .setPositiveButton("确定", (dialog, which) -> {
                    dialog.dismiss();
                    BLLocalFamilyManager familyManager = BLLocalFamilyManager.getInstance();
                    familyManager.addSdkDevice(device);
                    familyManager.addLocalDevice(device);
                    BLDeviceInfo blDeviceInfo = BLModelUtil.toBLDeviceInfo(device);
                    blDeviceInfo.setBlType(0);
                    familyManager.updateBLDeviceInfo(blDeviceInfo);
//                    familyManager.updateBLDevice(device, 0);
                });
        builder.show();
    }

    @Override
    public void onResume() {
        super.onResume();
        BLDeviceInfoDao deviceInfoDao = new BLDeviceInfoDao(getContext());
//        List<BLDeviceInfo> allBLDeviceInfo = deviceInfoDao.getFamilyBLDeviceInfos("");

        List<BLDNADevice> localDeviceInfos = new ArrayList<>();
        List<BLDeviceInfo> allBLDeviceInfo = deviceInfoDao.getAllBLDeviceInfo();
        if (allBLDeviceInfo != null && allBLDeviceInfo.size() > 0) {
            for (BLDeviceInfo deviceInfo : allBLDeviceInfo) {
                if (deviceInfo.getBlType() == 0) {
                    BLDNADevice bldnaDevice = deviceInfo.cloneBLDNADevice();
                    localDeviceInfos.add(bldnaDevice);
                }
            }
            mData.addAll(localDeviceInfos);
        }
        startProbe();
    }

    @Override
    public void onStop() {
        super.onStop();
        BLLet.Controller.stopProbe();
        BLLet.Controller.setOnDeviceScanListener(null);
    }

    private void startProbe() {
        BLLet.Controller.startProbe(3000);
        BLLet.Controller.setOnDeviceScanListener(new BLDeviceScanListener() {

            @Override
            public boolean shouldAdd(BLDNADevice device) {
                return super.shouldAdd(device);
            }

            @Override
            public void onDeviceUpdate(final BLDNADevice device, final boolean isNewDevice) {
//                mHandler.post(() -> updateDnaDevice(device, isNewDevice));

            }
        });
    }



//    private void updateDnaDevice(BLDNADevice device, boolean isNewDevice) {
//        Log.i(TAG, "onDeviceUpdate: isNewDevice = " + isNewDevice + " device = " + device.getName());
//        BLLocalFamilyManager familyManager = BLLocalFamilyManager.getInstance();
//        if (!isAddedDnaDevice(device)) {
//            mAdapter.addData(device);
//            familyManager.addSdkDevice(device);
//            familyManager.isUpdateBLDeviceFamilyId = false;
//            BLDeviceInfo blDeviceInfo = BLModelUtil.toBLDeviceInfo(device);
//            blDeviceInfo.setBlType(0);
//            familyManager.updateBLDeviceInfo(blDeviceInfo);
//        } else {
//            String did = device.getDid();
//            List<BLDNADevice> data = mAdapter.getData();
//            for (BLDNADevice bldnaDevice : data) {
//                if (bldnaDevice.getDid().equals(did)) {
//                    String newKey = device.getKey();
//                    if (!newKey.equals(bldnaDevice.getKey())) {
//                        if (did.equals(familyManager.mLocalDnaDevice.getDid())) {
//                            Log.i(TAG, "更新key: " + device.getName());
//                            familyManager.mLocalDnaDevice.setKey(newKey);
//                        }
//                        bldnaDevice.setKey(newKey);
////                        familyManager.updateBLDevice(device, 0);
//                        BLDeviceInfo blDeviceInfo = BLModelUtil.toBLDeviceInfo(device);
//                        blDeviceInfo.setBlType(0);
//                        familyManager.updateBLDeviceInfo(blDeviceInfo);
//                        mAdapter.notifyDataSetChanged();
//                    }
//                    break;
//                }
//            }
//        }
//    }
//
//    public boolean isAddedDnaDevice(BLDNADevice device) {
//        String did = device.getDid();
//        List<BLDNADevice> data = mAdapter.getData();
//        if (data.size() < 1) {
//            return false;
//        }
//        for (BLDNADevice bldnaDevice : data) {
//            if (bldnaDevice.getDid().equals(did)) {
//                return true;
//            }
//        }
//        return false;
//    }
}
